package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.RemindService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.oa.core.entity.com.Asset;
import com.fz.us.oa.core.entity.com.Certificate;
import com.fz.us.oa.core.entity.com.Purchase;
import com.fz.us.oa.core.entity.com.PurchaseItem;
import com.fz.us.oa.core.service.com.AssetService;
import com.fz.us.oa.core.service.com.PurchaseItemService;
import com.fz.us.oa.core.service.com.PurchaseService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/26.
 */
@Controller
@RequestMapping(value = "/com/purchase")
public class PurchaseController extends BaseController {
    private static final long serialVersionUID = 1993378719586174646L;

    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private PurchaseItemService purchaseItemService;
    @Autowired
    private AssetService assetService;
    @Autowired
    private RemindService remindService;

    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    private SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            Purchase purchase=purchaseService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("purchase", purchase);
        }
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/purchase_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            Purchase purchase=purchaseService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("purchase", purchase);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/purchase_read";
    }

    /**
     * 保存Model数据
     */
    private Purchase saveModel(User user, String keyId, String numStatus, String deptId, String applyReason,
                               String itemName, String itemPlanMoney, String itemFactMoney, String itemDatPurchase,
                               String planMoneySum ,String factMoneySum, String memo) throws ParseException {

        Purchase purchase = null;
        System.out.println("keyId:"+keyId);
        if (StringUtils.isBlank(keyId)) {
            purchase = new Purchase();
            purchase.setCreater(user);
            purchase.setCompany(user.getCompany());
        } else {
            purchase = purchaseService.get(keyId);
        }

        if(!StringUtils.isNotEmpty(numStatus)){
            numStatus="0";
        }

        int numS = Integer.valueOf(numStatus);
        System.out.println(numS);
        if (numS == 0) {
            if (StringUtils.isNotBlank(deptId)) {
                purchase.setIssueDepartment(departmentService.get(deptId));
            }

            if (StringUtils.isNotBlank(applyReason)) {
                purchase.setApplyReason(applyReason);
            }

            String[] nameArray = StringUtils.split(itemName,",");
            String[] planMoneyArray = StringUtils.split(itemPlanMoney,",");
            List<PurchaseItem> list = new ArrayList<PurchaseItem>();
            int len = nameArray.length;
            for (int i = 0; i < len; i++) {
                // 生成资产采购项目
                PurchaseItem purchaseItem = new PurchaseItem();
                purchaseItem.setCreater(user);
                purchaseItem.setCompany(user.getCompany());
                purchaseItem.setName(nameArray[i]);
                purchaseItem.setPlanMoney(Double.valueOf(planMoneyArray[i]));
                purchaseItemService.saveEntity(purchaseItem);
                list.add(purchaseItem);
            }
            purchase.setPurchaseItems(list);

            if (StringUtils.isNotBlank(planMoneySum)) {
                purchase.setPlanMoneySum(Double.valueOf(planMoneySum));
            }

            if (StringUtils.isNotBlank(memo)) {
                purchase.setMemo(memo);
            }

            if (purchase.getName() == null) {
                purchase.setName("资产采购登记");
            }

            if (purchase.getForm() == null) {
                purchase.setForm("资产采购登记表");
            }
        } else if (numS == 1) {
            String[] factMoneyArray = StringUtils.split(itemFactMoney,",");
            String[] datPurchaseArray = StringUtils.split(itemDatPurchase,",");
            List<PurchaseItem> list = purchase.getPurchaseItems();
            int len = factMoneyArray.length;
            for (int i = 0; i < len; i++) {
                // 写入对应的资产采购项目
                PurchaseItem purchaseItem = list.get(i);
                purchaseItem.setFactMoney(Double.valueOf(factMoneyArray[i]));
                purchaseItem.setDatPurchase(DataUtil.StringToDate(datPurchaseArray[i], "yyyy-MM-dd"));
                purchaseItemService.update(purchaseItem);
            }

            if (StringUtils.isNotBlank(factMoneySum)) {
                purchase.setFactMoneySum(Double.valueOf(factMoneySum));
            }
        }

        return purchase;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, @RequestParam(required = false) String keyId, String numStatus, String deptId, String applyReason,
                       String itemName, String itemPlanMoney, String itemFactMoney, String itemDatPurchase,
                       String planMoneySum ,String factMoneySum, String memo) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Purchase purchase = saveModel(user,keyId,numStatus,deptId,applyReason,itemName,itemPlanMoney,itemFactMoney,itemDatPurchase,planMoneySum,factMoneySum,memo);
        if(StringUtils.isNotEmpty(keyId)){
            purchaseService.update(purchase);
            rMap.put("message", "更新成功");
        } else {
            purchaseService.save(purchase, "com.fz.us.oa.core.entity.com.Purchase");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, @RequestParam(required = false) String keyId, String numStatus, String deptId, String applyReason,
                         String itemName, String itemPlanMoney, String itemFactMoney, String itemDatPurchase,
                         String planMoneySum ,String factMoneySum, String memo, String curDutyId, String comment) throws ParseException{

        Map<String,Object> rMap=new HashMap<String,Object>();
        Purchase purchase = saveModel(user,keyId,numStatus,deptId,applyReason,itemName,itemPlanMoney,itemFactMoney,itemDatPurchase,planMoneySum,factMoneySum,memo);
        purchase.setNumStatus(1);
        purchase.setTxtStatus("申请中");

        if (StringUtils.isNotEmpty(keyId)) {
            purchaseService.approve(purchase, dutyService.get(curDutyId), comment);
        } else {
            purchaseService.commit(purchase, "com.fz.us.oa.core.entity.com.Purchase", dutyService.get(curDutyId));
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Purchase purchase=purchaseService.get(keyId);
        purchaseService.approve(purchase, dutyService.get(curDutyId), comment);

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Purchase purchase=purchaseService.get(keyId);
            purchaseService.back(purchase, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Purchase purchase=purchaseService.get(keyId);
            purchaseService.deny(purchase, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //流转中
                searchResult = purchaseService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Purchase", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if(viewtype.equals("2")){
                //采购确认
                params.put("numStatus", 1);
                searchResult = purchaseService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Purchase", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //采购完成
                params.put("numStatus", 2);
                searchResult = purchaseService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Purchase", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }
        }else{
            //所有单子
            searchResult = purchaseService.paging(null,null,order,
                    "com.fz.us.oa.core.entity.com.Purchase",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }

        List<Purchase> purchaseList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Purchase purchase: purchaseList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(purchase.getId())?"":purchase.getId());

            if(purchase.getCreateTime() != null){
                Date dateApply = purchase.getCreateTime();
                rMap.put("year", yearFormat.format(dateApply));   // 年份
                rMap.put("month", monthFormat.format(dateApply));   // 月份
                rMap.put("dateApply",dateFormat.format(dateApply));
            } else {
                rMap.put("year", "");   // 年份
                rMap.put("month", "");   // 月份
                rMap.put("dateApply","");
            }

            rMap.put("creater", purchase.getCreater()==null?"": purchase.getCreater().getName());
            if(purchase.getIssueDepartment() != null){
                rMap.put("issueDepartment", purchase.getIssueDepartment().getName());
            } else {
                rMap.put("issueDepartment", "");
            }

            rMap.put("txtStatus", purchase.getTxtStatus());

//        rMap.put("processStateName", purchase.getProcessState()==null?"": purchase.getProcessState().value());
//        rMap.put("createTime", purchase.getCreateTime()==null?"": DataUtil.DateTimeToString(purchase.getCreateTime()));
//        rMap.put("dateApply", purchase.getDateApply()==null?"": DataUtil.DateTimeToString(purchase.getDateApply()));
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 采购完成操作
     */
    @RequestMapping(value = "finish", method = RequestMethod.POST)
    public Object finish(@CurrentUser User user, @RequestParam(required = false) String keyId, String numStatus, String deptId, String applyReason,
                         String itemName, String itemPlanMoney, String itemFactMoney, String itemDatPurchase,
                         String planMoneySum ,String factMoneySum, String memo) throws ParseException {

        Purchase purchase = saveModel(user, keyId, numStatus, deptId, applyReason, itemName, itemPlanMoney, itemFactMoney, itemDatPurchase, planMoneySum, factMoneySum, memo);

        if(purchase == null){
            return ajaxJson(resultService.fail("保存业务数据失败！"));
        }

        purchase.setNumStatus(2);
        purchase.setTxtStatus("采购完成");

         //完成后将采购条目根据资产类别自动拆分到资产台帐-“待入库”视图中中去
        List<PurchaseItem> list = purchase.getPurchaseItems();
        int len = list.size();
        Asset asset = null;
        for (int i = 0; i < len; i++) {
            PurchaseItem purchaseItem = list.get(i);
            asset = new Asset();
            asset.setCreater(user);
            asset.setCompany(user.getCompany());
            asset.setProcessState(FlowEnum.ProcessState.Finished);

            asset.setPurchase(purchase);
            asset.setForm("资产入库登记表");
            asset.setName(purchaseItem.getName());
            asset.setDatPurchase(purchaseItem.getDatPurchase());
            asset.setPurchaseMoney(purchaseItem.getFactMoney());
            asset.setTxtStatus("待入库");

            assetService.saveEntity(asset);
        }

        //发送提醒
        Remind remind = new Remind();
        remind.setUser(purchase.getCreater());
        remind.setBussinessKey("purchase");
        remind.setKeyId(keyId);
        remind.setContent("您的采购的物品已入库，可以进行后续领用");
        remindService.save(remind);

        return ajaxJson(purchaseService.saveEntity(purchase));
    }

    /**
     * 获取新建人部门
     * @return
     */
    @RequestMapping(value = "getDefaultDept", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public Object getDefaultDept(String curDutyId){
        Map<String, Object> data = new HashMap<String, Object>();
        Duty duty = dutyService.get(curDutyId);
        data.put("department",duty.getPower().getDepartment().getName());
        data.put("departmentId", duty.getPower().getDepartment().getId());
        return  ajaxJson(data);
    }


}
